package com.sanglh.tutorial.windowmanager;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageButton;

import com.sanglh.tutorial.R;

public class WindowService extends Service implements OnClickListener {
	private static final String ACTION_LOCK_SCREEN = "ACTION_LOCK_SCREEN";
	private static final String ACTION_UNLOCK_SCREEN = "ACTION_UNLOCK_SCREEN";
	private WindowManager mWindowManager;
	private LayoutParams mWindowParams;
	private View mLockScreen;

	public static void clock(Context context) {
		Intent service = new Intent(ACTION_LOCK_SCREEN);
		service.setClass(context, WindowService.class);
		context.startService(service);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent == null) {
			return START_STICKY;
		}
		String action = intent.getAction();
		if (action.equalsIgnoreCase(ACTION_LOCK_SCREEN)) {
			onClock();
		} else if (action.equalsIgnoreCase(ACTION_UNLOCK_SCREEN)) {
			unLock();
		}
		return START_STICKY;
	}

	private void onClock() {
		((ImageButton) mLockScreen.findViewById(R.id.imgbtn_lock))
				.setOnClickListener(WindowService.this);
		addView(mLockScreen, mWindowParams);
	}

	private void unLock() {
		removeView(mLockScreen);
	}

	private void addView(View view, LayoutParams params) {
		if (view == null || params == null) {
			return;
		}
		mWindowManager.addView(view, params);
	}

	private void removeView(View view) {
		if (view == null) {
			return;
		}
		mWindowManager.removeView(view);
	}

	@Override
	public void onCreate() {
		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		mWindowParams = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, 0, 0,
				LayoutParams.TYPE_SYSTEM_ERROR, LayoutParams.FLAG_FULLSCREEN
						| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
						| LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
						| LayoutParams.FLAG_NOT_TOUCH_MODAL,
				PixelFormat.TRANSLUCENT);
		mLockScreen = LayoutInflater.from(this).inflate(
				R.layout.view_window_lock_screen, null);
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imgbtn_lock:
			unLock();
			break;

		default:
			break;
		}

	}

}
